const path = require('path')

const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const HtmlWebpackPlugin = require('html-webpack-plugin')

const { CleanWebpackPlugin } = require('clean-webpack-plugin')

const glob = require('glob')

const testPlugin = require('./plugin/testPlugin')

// 设置多页面
const setMpa = () => {
    const entry = {}
    const plugins = []

    // 拿到所有的入口文件
    const entryFiles = glob.sync(path.resolve(__dirname, './src/pages/*/index.js'))

    entryFiles.forEach(entryFile => {
        const match = entryFile.match(/src\/pages\/(.*)\/index\.js$/)
        const chunkName = match[1]
        entry[chunkName] = entryFile
        plugins.push(new HtmlWebpackPlugin({
            template: `./src/pages/${chunkName}/index.html`,
            filename: `${chunkName}.html`,
            chunks: [chunkName]
        }))
    })

    return {
        entry,
        plugins
    }
}

const { entry, plugins } = setMpa()

module.exports = {
    entry,
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, './dist')
    },
    mode: 'development',
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader'
                ]
            },
            {
                test: /\.(png|jpe?g|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        name: '[name].[ext]',
                        limit: 1024 * 3,
                        outputPath: 'img/',
                        publicPath: '/img'
                    }
                }
            },
            {
                test: /\.js$/,
                use: path.resolve(__dirname, './loader/testLoader.js')
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'css/[name].css'
        }),
        new CleanWebpackPlugin(),
        new testPlugin(),
        ...plugins
    ],
    devServer: {
        port: 8888,
        open: true
    }
}